﻿using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Windows.Data;
using System.Windows.Media.Imaging;

namespace Coding4Fun.FakeCall.Converters
{
	public class ImageConverter : IValueConverter
	{
		#region IValueConverter Members

		public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
		{
			try
			{
				if (value is string && !string.IsNullOrEmpty(value as string))
				{
					var fn = value as string;
					using (var myStore = IsolatedStorageFile.GetUserStoreForApplication())
					{
						if (myStore.FileExists(fn))
						{
							using (var photoStream = myStore.OpenFile(fn, FileMode.Open))
							{
								var bs = new BitmapImage();
								bs.SetSource(photoStream);
								return bs;
							}
						}
						else
						{
							return (new BitmapImage(new Uri(fn, UriKind.Relative)));
						}
					}
				}
			}
			catch (Exception x) { }

			// If all else fails...
			return null;
		}

		public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
		{
			throw new NotImplementedException();
		}

		#endregion
	}
}
